<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 用户优惠券管理
 */
namespace app\allwin\model;
use app\allwin\model\CouponLog;
use app\allwin\model\Coupon;
use think\Model;
use think\facade\Log;
class CouponUser extends Model{

    protected $pk = 'id';
    protected $table = 'ai_allwin_coupon_user';

    /**
     * 好店
     * @return void
     */
    public function store(){
        return $this->hasOne('AllwinStore','id','store_id');
    }

    /**
     * 用户
     * @return void
     */
    public function user(){
        return $this->hasOne('app\common\model\SystemUser','id','uid');
    } 
    
    /**
     * 优惠券
     * @return void
     */
    public function coupon(){
        return $this->hasOne('Coupon','id','coupon_id');
    } 

    /**
     * 用户优惠券减少(支付通知调用本函数)
     * @path allwin\controller\v4\Notify\storeWechat();
     * @param array $param
     * @return void
     */
    public static function userCouponPay($param){
        if(!$param->coupon_price){
            return;
        }
        $coupon = self::where(['id' => $param->coupon_user_id,'uid' => $param->uid,'is_end' => 0])->find();
        if(empty($coupon)){
            return;
        }
        $data = [];
        if($param->coupon_price <= $coupon->user_size){
            $user_size = $coupon->user_size - $param->coupon_price;
            $data['user_size'] = $user_size;
        }else{
            $user_size = 0;
            $data['user_size'] = $user_size;
            $data['is_end']    = 1;
        }
        self::where(['id' => $coupon->id])->update($data);  //更新状态
        $rule = [];
        $rule['member_miniapp_id'] = $param->member_miniapp_id;
        $rule['uid']               = $param->uid;
        $rule['coupon_id']         = $param->coupon_user_id;
        $rule['amount']            = $param->coupon_price;
        $rule['times']             = $param->paid_time;
        return CouponLog::insert($rule);
    }
    /**
     * 单独添加用户优惠券
     * @param array $ids  优惠券的ID
     * @param integer $uid  用户ID
     * @return void
     */
    public static function createUserCoupon($coupon_id,int $uid){
        $coupon = Coupon::where(['id' => $coupon_id])->find();
        if(empty($coupon)){
            return;
        }
        $data = [];
        $data['uid']               = $uid;
        $data['member_miniapp_id'] = $coupon['member_miniapp_id'];
        $data['store_id']          = $coupon['store_id'];
        $data['coupon_id']         = $coupon['id'];
        $data['types']             = $coupon['types'];
        $data['name']              = $coupon['name'];
        $data['size']              = $coupon['size'];
        $data['user_size']         = $coupon['size'];
        $data['price']             = $coupon['price'];
        $data['discount']          = $coupon['discount'];
        $data['weekday']           = $coupon['weekday'];
        $data['howmuch']           = $coupon['howmuch'];
        $data['starttime']         = $coupon['starttime'];
        $data['endtime']           = $coupon['endtime'];
        $data['tips']              = $coupon['tips'];
        $data['longtime']          = $coupon['longtime'];
        $data['daynumss']          = $coupon['daynum'];
        $data['ontypes']           = $coupon['ontypes'];
        $data['is_end']            = 0;
        $data['update_time']       = time();
        $data['create_time']       = time();
        $coupon->num = ['inc', 1];
        $coupon->save();
        return CouponUser::create($data);
    }

    /**
     * 批量添加优惠券
     * @param array $ids  优惠券的ID
     * @param integer $uid  用户ID
     * @return void
     */
    public static function addUserCoupon($ids,int $uid){
        $ids = json_decode($ids,true);
        if(empty($ids)){
            return;
        }
        $coupon = new Coupon;
        $lists = $coupon->where(['id' => $ids])->select();
        if(empty($lists)){
            return;
        }
        $data = [];
        $coupon_num = [];
        foreach ($lists as $key => $value) {
            $data[$key]['uid']               = $uid;
            $data[$key]['member_miniapp_id'] = $value['member_miniapp_id'];
            $data[$key]['store_id']          = $value['store_id'];
            $data[$key]['coupon_id']         = $value['id'];
            $data[$key]['types']             = $value['types'];   
            $data[$key]['name']              = $value['name'];
            $data[$key]['size']              = $value['size'];
            $data[$key]['user_size']         = $value['size'];
            $data[$key]['price']             = $value['price'];
            $data[$key]['discount']          = $value['discount'];
            $data[$key]['weekday']           = $value['weekday'];
            $data[$key]['howmuch']           = $value['howmuch'];
            $data[$key]['starttime']         = $value['starttime'];
            $data[$key]['endtime']           = $value['endtime'];
            $data[$key]['tips']              = $value['tips'];
            $data[$key]['longtime']          = $value['longtime'];
            $data[$key]['daynum']            = $value['daynum'];
            $data[$key]['ontypes']           = $value['ontypes'];
            $data[$key]['is_end']            = 0;
            $data[$key]['update_time']       = time();
            $data[$key]['create_time']       = time();
            $coupon_num[$key]['num'] = $value['num']-1;
            $coupon_num[$key]['id']  = $value['id'];
        }
        $rel = self::insertAll($data);
        if($rel){
            return $coupon->saveAll($coupon_num);
        }
        return;
    }

    /**
     * 返回我所有正常能使用未过期和未使用完的优惠券
     * @param integer $uid  用户ID
     * @param integer $store_id  店铺ID
     * @return array
     */
    public static function userCouponIds(int $uid,int $coupon_id = 0,int $store_id = 0){
        $condition = self::condition($uid,$coupon_id,$store_id);
        $coupon = self::where($condition)->field('uid,store_id,coupon_id')->select()->toArray();
        return empty($coupon) ? [] : array_unique(array_column($coupon,'coupon_id'));
    }

    /**
     * 统计某个优惠券、某个好店、某个用户正常的优惠券数量
     * @param integer $uid
     * @param integer $store_id
     * @return void
     */
    public static function userCouponCount(int $uid,int $coupon_id = 0,int $store_id = 0){
        $condition = self::condition($uid,$coupon_id,$store_id);
        return self::where($condition)->field('uid,store_id,coupon_id')->count();
    }
       
    //查询某个用户的优惠券列表(API)
    public static function userCoupon(array $condition,int $page = 10){
        return self::with('store')->where($condition)->order('id desc')->paginate($page,true);
    }

    //无翻页
    public static function userStoreCoupon(array $condition){
        return self::with('store')->where($condition)->select();
    }

    //查询单个优惠券
    public static function getuser(array $condition){
        return self::with('store')->where($condition)->find();
    }

    /**
     * #####################################################
     * 返回查询条件 function
     * @param integer $uid
     * @param integer $coupon_id
     * @param integer $store_id
     * @return array
     */
    public static function condition(int $uid,int $coupon_id = 0,int $store_id = 0){
        $times       = time(); //获取现在的时间
        $condition   = [];
        $condition[] = ['uid','=',$uid];
        $condition[] = ['endtime','>',$times];
        $condition[] = ['is_end','=',0];
        $condition[] = ['user_size','>',0];
        if($store_id){
            $condition[] = ['store_id','=',$store_id];
        }
        if($coupon_id){
            $condition[] = ['coupon_id','=',$coupon_id];
        }
        return $condition;
    } 
}